<template>
    <div>
        <br/>
        <br/>
        <el-form ref="route" :model="ltname" >
            <el-form-item label="活动名称" :label-width="formLabelWidth">
                <el-input placeholder="请输入内容" v-model="ltname.labelName" class="input-with-select" clearable>
                    <el-button slot="append" @click="listByRoute('labelName')" icon="el-icon-search"></el-button>
                </el-input>
            </el-form-item>
        </el-form>

        <el-button type="primary" round @click="dialogFormVisible = true" plain>新增活动</el-button>

        <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="resetForm"> <!--取消后清空表格中数据-->
            <el-form :model="empInfo" :rules="rules" ref="empInfo">
                <el-form-item label="活动名称" :label-width="formLabelWidth" prop="labelName">
                    <el-input placeholder="请输入活动名称" v-model="empInfo.labelName" ></el-input>
                </el-form-item>
                <el-form-item label="活动详情" :label-width="formLabelWidth" prop="shortDesc">
                    <el-input type="textarea" :rows="5" placeholder="请输入活动详情" v-model="empInfo.shortDesc"></el-input>
                </el-form-item>

                <el-form-item label="活动时间" :label-width="formLabelWidth" prop="activityTime">
                    <el-date-picker class="activityWidth"
                        :picker-options="pickerOption"
                        v-model="empInfo.activityTime"
                        type="datetimerange"getUrl
                        value-format="yyyy-MM-dd HH:mm:ss"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>

                <el-form-item label="活动图片" :label-width="formLabelWidth" >
                    <img class="productPicWidth" :src="getUrl(defaultPic)" alt="">
                    <el-upload
                        class="upload-demo"
                        :action="insertUrl()"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                    >
                        <el-button size="mini">更新图片</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="resetForm">取 消</el-button>
                <el-button type="primary" @click="sub('empInfo')">确 认</el-button>
            </div>
        </el-dialog>

        <hr/>

        <el-table :data="data"
                  tooltip-effect="dark"
                  style="width: 100%"
                  @selection-change="handleSelectionChange">
            <el-table-column prop="tid" label="活动编号"></el-table-column>
            <el-table-column prop="labelName" label="活动名称" width="170px"></el-table-column>
            <el-table-column prop="picPath" label="活动图片">
                <template slot-scope="scope">
                    <img class="productPicWidth" :src="getUrl(scope.row.picPath)" alt="">
                </template>
            </el-table-column>
            <el-table-column prop="shortDesc" label="活动详情" width="200px"></el-table-column>
            <el-table-column prop="startTime" label="开始时间" width="170px"></el-table-column>
            <el-table-column prop="finishTime" label="结束时间" width="170px"></el-table-column>
            <el-table-column prop="state" label="状态">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.state === 0" @click="updateState(scope.row)">活动正常</el-tag>
                    <el-tag type="danger" v-if="scope.row.state === 1" @click="updateState(scope.row)">活动未上架</el-tag>
                    <el-tag type="primary" @click="goActivityPage(scope.row)">活动详情</el-tag>
                </template>

            </el-table-column>

            <el-table-column  label="编辑操作">
                <template slot-scope="scope">
                    <i class="el-icon-edit" @click="update(scope.row)"></i>
                </template>
            </el-table-column>
        </el-table>
        <br/>
        <div class="page">
            <el-pagination
                background
                center
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="currentPage"
                :page-size="pageSize"
                :page-sizes="pageList"
                layout="total, sizes, prev, pager, next, jumper"
                :total="list.length">
                <!--           layout加上 sizes,    :page-sizes="[6, 7, 8, 9 ,10]"-->
            </el-pagination>
        </div>
    </div>
</template>

<script>
    export default {
        name: "activity",
        inject:['reload'],//注入reload方法
        data() {
            return {
                // 活动开始时间限制
                pickerOption:{
                    disabledDate(time) {
                        return time.getTime() <= (Date.now() - 86400000 );
                    }
                },
                // 默认图片
                defaultPic: "1.jpg",
                // 当前页
                currentPage: 1,
                // 每页显示 5 条数据
                pageSize: 5,
                // 每页显示多少条数据的数组
                pageList: [5, 10, 15, 20],
                list: [],
                empInfo: {

                },
                proinfo:[],
                ttt: false,
                ltname: {
                    labelName: null
                },
                dialogFormVisible: false,
                dialogFormVisibleUp: false,
                formLabelWidth: '120px',
                title: "新增活动",
                rules: { //校验输入框输入规则
                    labelName:[
                        { required: true, message: '请输入商品名称', trigger: 'blur' },
                        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
                    ],
                    shortDesc:[
                        { required: true, message: '请输入商品详情', trigger: 'blur' },
                        { min: 5, max: 150, message: '长度在 5 到 150 个字符', trigger: 'blur' }
                    ],
                    store:[
                        { required: true, message: '请输入商品库存', trigger: 'blur'},
                        { type: 'number', message: '必须为数字值', trigger: 'blur'}
                    ],
                    activityTime:[
                        { required: true, message: '请输入活动时间', trigger: 'blur'},
                    ],
                }
            }
        },
        created() {
            this.$http.post("product/activity/selectAll").then(data => {
                this.list = data.data;
            })
        },
        computed: {
            // 计算分页所显示的数据
            data() {
                if(this.list != null){
                    // 使用 splice 方法从第几个开始取出多少条数据
                    return this.list.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                }
            }
        },
        methods: {
            // 修改当前页显示 多少数据
            handleSizeChange(val) {
                // console.log(`每页 ${val} 条`);
                this.pageSize = val;
            },
            // 修改当前是 第几页
            handleCurrentChange(val) {
                // console.log(`当前页: ${val}`);
                this.currentPage = val;
            },
            selPrice(tid){
                console.log(tid)
                /*this.$http.post(`product/product/findById/${tid}`).then(data => {
                    this.empInfo.oldPrice = data.data.price;
                })*/
            },
            sub(formName) {
                // 对整个表单进行校验
                this.$refs[formName].validate((valid) => {
                    this.empInfo.picPath = this.defaultPic;
                    if (valid) {
                        this.empInfo.startTime = this.empInfo.activityTime[0];
                        this.empInfo.finishTime = this.empInfo.activityTime[1];
                        console.log(this.empInfo)
                        this.$http.post("product/activity/saveOrUpdate", this.empInfo).then(data => {
                            if (data) {
                                // alert("数据改变");
                                this.$message({
                                    type: 'success',
                                    message: '成功!'
                                });
                                this.reload()//直接调用刷新方法
                            } else {
                                this.$message({
                                    type: 'info',
                                    message: '失败!'
                                });
                                this.reload()//直接调用刷新方法
                            }
                        })
                    } else {
                        console.log('error submit!!')
                        return false;
                    }
                })
            },
            update(row) {
                this.title = '修改活动信息'
                this.ttt = true
                this.$http.post(`product/activity/findById/${row.tid}`).then(data => {
                    this.empInfo = data.data;
                    this.$set(this.empInfo,'activityTime',[new Date(this.empInfo.startTime),new Date(this.empInfo.finishTime)]);
                    console.log(this.empInfo)
                })
                this.dialogFormVisible = true
            },
            handleSelectionChange(val) {
                console.log(val)
                this.multipleSelection = [];
                for (let valKey in val) {
                    this.multipleSelection.push(val[valKey].tid)
                }
            },
            resetForm() {
                this.dialogFormVisible = false
                this.reload();
            },
            listByRoute() {
                if (this.ltname.labelName == null) {
                    this.$http.post("product/activity/selectAll").then(data => {
                        this.list = data.data;
                    })
                    this.reload();
                } else {
                    this.$http.post("product/activity/listByLname", this.ltname).then(data => {
                        this.list = data.data;
                    })
                }
            },
            updateState(row) {
                this.$confirm('此操作将修改此商品状态, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'success'
                }).then(() => {
                    if (row.state == 0) {
                        this.$http.post("product/activity/saveOrUpdate", {state: 1, tid: row.tid}).then(data => {
                            this.$message({
                                type: 'success',
                                message: '成功!'
                            });
                            this.reload();
                        })
                    } else if (row.state == 1) {
                        this.$http.post("product/activity/saveOrUpdate", {state: 0, tid: row.tid}).then(data => {
                            this.$message({
                                type: 'success',
                                message: '成功!'
                            });
                            this.reload();
                        })
                    } else {
                        this.$message({
                            type: 'info',
                            message: '请求错误!'
                        });
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消修改'
                    });
                });
            },
            // 图片上传成功之后调用的方法
            handleAvatarSuccess (res, file) {
                /*console.log("上传的结果")
                console.log(res);
                console.log("上传的文件信息")
                console.log(file)*/
                if (res.code === 1) {
                    this.defaultPic = res.pic;
                    this.$message({
                        message: '上传成功',
                        type: 'success'
                    })
                } else {
                    this.notify('上传失败', 'error')
                }
            },
            // 图片上传之前调用的方法，验证上传的是否是图片
            beforeAvatarUpload (file) {
                const isJPG = file.type === 'image/jpeg'
                const isLt2M = file.size / 1024 / 1024 < 10
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!')
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片不符合规范!')
                }
                return isJPG && isLt2M
            },
            // 上传图片
            insertUrl(){
                return `http://localhost:8092/product/activity/insertProductPic`;
            },
            // 获取图片
            getUrl (picPath) {
                return `http://localhost:8092/product/activity/findProductPicByPath?name=`+picPath;
            },
            // 跳转到活动详情界面
            goActivityPage(row){
                this.$store.commit("setActivity",row)
                this.$router.push("activityContent")
            }
        }
    }
</script>

<style scoped>
    .activityWidth{
        width: 100%;
    }
    .productPicWidth{
        width: 100px;
        height: 100px;
    }
</style>
